﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Text;
using System.Linq;

/* Examples:
 * https://gdata.youtube.com/feeds/api/videos/VWADjnwSQVA?v=2
*/ 

namespace DevSky.WebParts.YouTube
{
    [ToolboxItemAttribute(false)]
    public partial class YouTubeCarousel : Microsoft.SharePoint.WebPartPages.WebPart
    {
        private List<SingleVideo> channelVideoList = null;

        #region Controls
        private Panel videoCarouselContainer = null;                
        #endregion

        private bool IsErrorOnRendering { get; set; }

        protected override void OnInit(EventArgs e)
        {
            videoCarouselContainer = new Panel() { ID = "videoCarouselContainer" };
            RegisterResources();
            base.OnInit(e);
        }

        private void RegisterResources()
        {
            // TODO MAZ: MOVE resources to res-file to suport sandoxed solutions
            #region Styles
            CssLink cssLink = new CssLink();
            cssLink.DefaultUrl = "/_layouts/DevSkyYouTubeWebPartSuite/jCarouselSkins/ie7/skin.css";
            Page.Header.Controls.Add(cssLink);

            cssLink = new CssLink();
            cssLink.DefaultUrl = "/_layouts/DevSkyYouTubeWebPartSuite/css/jquery.fancybox-1.3.4.css";
            Page.Header.Controls.Add(cssLink);
            #endregion
            #region ADD jQuery support
            Page.ClientScript.RegisterClientScriptInclude("jquery", "/_layouts/DevSkyYouTubeWebPartSuite/JavaScript/jquery-1.7.1.min.js");
            Page.ClientScript.RegisterClientScriptInclude("jcarusel", "/_layouts/DevSkyYouTubeWebPartSuite/JavaScript/jquery.jcarousel.js");
            #endregion
            #region ADD FancyBox
            Page.ClientScript.RegisterClientScriptInclude("fancyBoxCore", "/_layouts/DevSkyYouTubeWebPartSuite/JavaScript/jquery.fancybox-1.3.4.js");
            Page.ClientScript.RegisterClientScriptInclude("fancyBoxEasing", "/_layouts/DevSkyYouTubeWebPartSuite/JavaScript/jquery.easing-1.3.pack.js");
            #endregion
        }

        protected override void CreateChildControls()
        {
            
            if (SPContext.Current.FormContext.FormMode == SPControlMode.Edit)
            {
                Controls.Add(new Label() { Text = "Videos are not displayed in edit mode!" });
            }
            else
            {
                if ((!string.IsNullOrEmpty(ChannelName)) && GetChannelVideos != null && GetChannelVideos.Count > 0)
                {
                    HtmlGenericControl ul = new HtmlGenericControl("ul") { ID = "youTubeVideoList" };
                    ul.Attributes.Add("class", "jcarousel-skin-ie7");
                    ul.Style.Add("display", "none");
                    videoCarouselContainer.Controls.Add(ul);
                    HtmlGenericControl li = null;

                    List<SingleVideo> renderList = GetChannelVideos;
                    if (ShowOnlySpecifiedVideos)
                        renderList = GetChannelVideos.Where(v => VideoLink.Contains(v.ID)).ToList();

                    // Find attitional video from other channels

                    foreach (string vid in VideoLink.Split(new char[] { ';' }))
                    {
                        if ((!string.IsNullOrEmpty(vid)) && renderList.Where(video => video.ID.Equals(vid)).Count() == 0)
                        {
                            renderList.Add(YouTubeManager.GetVideoInformation(vid));
                        }
                    }

                    foreach (SingleVideo video in renderList)
                    {
                        li = new HtmlGenericControl("li");
                        li.Controls.Add(SingleVideoEntry(video));
                        ul.Controls.Add(li);
                    }
                    Controls.Add(videoCarouselContainer);
                    RegisterStartupScript(ul.ClientID);
                }
                else
                {
                    Controls.Add(new Label() { Text = "No videos found or no youtube channel defined!" });
                }
            }
        }

        private void RegisterStartupScript(string listID)
        {
            StringBuilder scriptBlock = new StringBuilder("jQuery(document).ready(function() { ");
            scriptBlock.AppendFormat("$('#{0}').jcarousel({{ vertical : false }}); ", listID);            
            // add fancy box
            scriptBlock.Append("$('a[id$=\"youtubeVideoEntry\"]').fancybox({ ");
            scriptBlock.Append("'padding': 0, 'autoScale' : false, 'transitionIn' : 'elastic', 'transitionOut' : 'elastic', ");
            scriptBlock.Append("'speedIn' : 600, 'speedOut' : 200, 'title' : this.title, 'width' : 800, 'height' : 600, ");
            scriptBlock.Append("'type' : 'swf', 'swf' : { 'wmode' : 'transparent', 'allowfullscreen' : 'true' } });");
            // End Fancy box

            scriptBlock.AppendFormat("$('#{0}').css('display', 'block'); ", listID);            

            scriptBlock.Append("});"); // END START METHODE
            Page.ClientScript.RegisterClientScriptBlock(typeof(YouTubeCarousel),"INITCAROUSEL", scriptBlock.ToString(),true);
        }

        private HtmlAnchor SingleVideoEntry(SingleVideo videoData)
        {
            Panel container = new Panel() { ID = videoData.ID };
            container.CssClass = "ytVideoEntry";
            Panel videoWrapper = new Panel();
            container.Controls.Add(videoWrapper);
            Image thumbnail = new Image() { ImageUrl = videoData.Thumbnails[0].Url };
            thumbnail.Style.Add("width", "150px"); // TODO MAZ CONFIG
            thumbnail.Style.Add("height", "120px"); // TODO MAZ CONFIG - calculate from the web part dimension
            videoWrapper.Controls.Add(thumbnail);
            videoWrapper.Controls.Add(new HtmlGenericControl("br"));
            videoWrapper.Controls.Add(new Label() { Text = videoData.Title });
            HtmlAnchor anchor = new HtmlAnchor() { ID = string.Format("{0}youtubeVideoEntry", videoData.ID) };
            anchor.Controls.Add(container);
            anchor.Title = videoData.Title;
            anchor.HRef = videoData.ShortLink;
            return anchor;
        }

        private List<SingleVideo> GetChannelVideos
        {
            get
            {
                if (channelVideoList == null)
                    channelVideoList = YouTubeManager.GetVideoForChannel(ChannelName);
                return channelVideoList;
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            if (!IsErrorOnRendering)
            {
                try
                {
                    base.OnLoad(e);
                    this.EnsureChildControls();
                }
                catch (Exception ex)
                {
                    HandleException(ex);
                }
            }
            IsErrorOnRendering = false;
        }

        #region Helper
        private void HandleException(Exception ex)
        {
            this.IsErrorOnRendering = true;
            this.Controls.Clear();
            this.Controls.Add(new LiteralControl(ex.Message));
        }
        #endregion
    }
}
